package com.epam.facebook_client.task;

import java.io.IOException;

import org.json.JSONException;

import android.content.Context;
import android.os.AsyncTask;
import android.view.View;

import com.epam.facebook_client.manager.HttpClientManager;

public abstract class CommonAsyncTask<T> extends AsyncTask<String, Void, T> {

	private static final String TAG = CommonAsyncTask.class.getSimpleName();
	private Exception mError;
	private String url;
	
	protected Context context;
	protected View view;
	

	public CommonAsyncTask(Context context) {
		this(context, null);
	}

	public CommonAsyncTask(Context context, View view) {
		this.context = context;
		this.view = view;
	}

	@Override
	protected void onPreExecute() {
		if (view != null) {
			view.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected T doInBackground(String... arg) {
		try {
			url = arg[0];
			return convert(load(arg[0]));
		} catch (Exception e) {
			this.mError = e;
		}
		return null;
	}

	private String load(String pUrl) throws IOException {
		if (context != null) {
			return HttpClientManager.get(context).loadAsString(pUrl);
		}
		return null;
	}

	@Override
	protected void onPostExecute(T result) {
		super.onPostExecute(result);
		if (mError == null) {
			if (view != null) {
				view.setVisibility(View.GONE);
			}
			success(result);
		} else {
			onError(mError);
		}
	}
	
	public String getUrl(){
		return url;
	}

	protected abstract void success(T result);

	protected abstract T convert(String str) throws JSONException;

	protected abstract void onError(Exception e);

}
